package com.sap.health.tracker;
 
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
import com.sap.health.tracker.json.JSONFunctions;
import com.sap.health.tracker.library.StoreData;
 
public class LoginActivity extends Activity {
	
	// inputs and error texts.
    private EditText mInputUsername;
    private EditText mInputPassword;
    private TextView mIoginErrorMsg;
 
    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_UID = "uid";
    private static String KEY_SESSION = "session";
    private static String KEY_ROLE = "role";
    
    //progress dialog pops up when loading.
    private ProgressDialog mLoadingDialog; 
    
    private Context mCtx;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // use this context
        mCtx = this;        
        // splash screen is shown until loading has completed.
        setContentView(R.layout.splash);     
        // checks to see if the user is already logged in.
        checkLogin();  
    }       
    /*
     * Check the login status. If logged in, go to main layout, if not,
     * go to login layout.
     */
    private void checkLogin(){
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			// Create new JSON function class.
		    	JSONFunctions userFunctions = new JSONFunctions();	    	
		    	//open local storage connection
		        StoreData store = new StoreData();
		        // get user id from local storage
		        String userId = (String) store.openType(mCtx, String.class, 
		        		KEY_UID);
		        // get session token from local storage
		        String session = (String) store.openType(mCtx, String.class, 
		        		KEY_SESSION);
		        //check if local session is stored.
		        if(userId != null || userId != "" || session != null || 
		        		session != ""){
			        // connect to server and login.
		        	JSONObject json = userFunctions.checkLoginUser(userId, 
		        			session);
			        // check for login response
			        try {
			        	if (json.getString(KEY_SUCCESS) != null) { // success
			        		json.getJSONObject("user");
			             	String res = json.getString(KEY_SUCCESS);
			                if(Integer.parseInt(res) == 1){		// success okay.                 		                			                	
                            	// Launch Main Screen
	                            Intent main = new Intent(
	                            		getApplicationContext(), Main.class);
	                            // Close all views before launching Main
	                            main.addFlags(
	                            		Intent.FLAG_ACTIVITY_CLEAR_TOP);
	                            startActivity(main);
	                            // Close Registration Screen
	                            finish();                      
	                           
			                 } else{
				            	 // not logged in, get login screen.
				            	 runOnUiThread(new Runnable() {
				                     public void run() {
				                    	 loginSetup();			                     
				                     }
				                 });
				             }
			             } else{
			            	 // not logged in, get login screen.
			            	 runOnUiThread(new Runnable() {
			                     public void run() {
			                    	 loginSetup();			                     
			                     }
			                 });
			             }
			         } catch (Exception e) {
			        	 //TODO catch other exceptions instead of generaic.
			        	 System.out.println("Check Login: " + e);
			        	 runOnUiThread(new Runnable() {
		                     public void run() {
		                    	 loginSetup();			                     
		                     }
		                 });
			         }
		        } 
	        	runOnUiThread(new Runnable() {
                     public void run() {
                    	 loginSetup();			                     
                     }
                 });        
            }        	
    	}).start();
    }  
    /*
     * Once login check finishes, start the login if not logged in.
     */
    private void loginSetup(){
    	// show login layout.
        setContentView(R.layout.login);                     
        // Importing all assets like buttons, text fields
        mInputUsername = (EditText) findViewById(R.id.loginUsername);
        mInputPassword = (EditText) findViewById(R.id.loginPassword);
        Button btnLogin = (Button) findViewById(R.id.btnLogin);
        Button btnLinkToRegister = (Button) 
        		findViewById(R.id.btnLinkToRegisterScreen);
        mIoginErrorMsg = (TextView) findViewById(R.id.login_error);
 
        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {          	
            	// Run login on new thread
            	loginThread();      
            }
        });
 
        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });
    } 
    /*
     * When logging in, we run from a thread so the main UI doesn't become 
     * unresponsive.
     */
    public void loginThread(){
    	new Thread(new Runnable() {
    		@Override
    		public void run() {         	
            	runOnUiThread(new Runnable() {
            		public void run() {
            			// show progress spinner to let user know it's working.
                    	showProgress();
                    }
                });
            	// get string from EditText fields
            	String username = mInputUsername.getText().toString();
                String password = mInputPassword.getText().toString();
                //create new JSON function class.
                JSONFunctions userFunction = new JSONFunctions();
                // connect to server and login.
                JSONObject json = userFunction.loginUser(username, password);
                // check for login response
                try {
                	// make sure the server didn't have any problems.
                	if (json.getString(KEY_SUCCESS) != null) {
                		runOnUiThread(new Runnable() {
                			public void run() {
                				// clear the error message for the user.
                            	mIoginErrorMsg.setText("");
                            }
                		});
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                            // get object from server connection.
                        	JSONObject json_user = json.getJSONObject("user");                       
                            //save session token to local storage
                            StoreData store = new StoreData();
                            //store user id
                            store.saveType(mCtx, String.class, KEY_UID, json.getString(KEY_UID));
                            //store session token
                            store.saveType(mCtx, String.class, KEY_SESSION, json_user.get(KEY_SESSION));
                            //store role type
                            store.saveType(mCtx, String.class, KEY_ROLE, json_user.get(KEY_ROLE));                            
                         	// Launch Main Screen
                            Intent main = new Intent(getApplicationContext(), Main.class);
                            // Close all views before launching main
                            main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(main);
                            // Close Registration Screen
                            finish();
                             
                         }else{
                         	runOnUiThread(new Runnable() {
                                 public void run() {
                                 	// Error in login
                                	 mIoginErrorMsg.setText("Incorrect username/password");
                                 }
                             });
                         }
                     }
                 } catch (Exception e) {
                     //TODO catch specific exceptions, not generic.
                	 System.out.println("loginThread(): " + e);              		        	 
                     runOnUiThread(new Runnable() {
                         public void run() {
                         	// Error in login
                        	 mIoginErrorMsg.setText("Network Connection Error");
                         }
                     });
		        	 
                 }
                 runOnUiThread(new Runnable() {
                     public void run() {
                     	//  hide progress dialog, we're done.
                    	 hideProgress();
                     }
                 });
            }   
                 	
    	}).start();
    }   
    /*
     * When finished loading, get rid of loading dialog.
     */
    private void hideProgress(){
    	mLoadingDialog.dismiss();
    }
    /*
     * Create new progress dialog and display it.
     */
    private void showProgress(){
    	mLoadingDialog = new ProgressDialog(mCtx);
    	mLoadingDialog.setTitle("");
    	mLoadingDialog.setMessage("Loading. Please wait...");
    	mLoadingDialog.show();
    }    
}